﻿using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WhutDoomCheck.Server.Configs;
using WhutDoomCheck.Server.Entities;
using WhutDoomCheck.Server.Extentions;
using WhutDoomCheck.Server.Services;
using WhutDoomCheck.Shared.HttpModels;

namespace WhutDoomCheck.Server.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(IdentityPolicyNames.Teacher)]
    public class TeacherController : ControllerBase
    {
        public TeacherController(ApplicationDbContext dbContext, RecordService recordService, ExportService exportService)
        {
            this.dbContext = dbContext;
            this.recordService = recordService;
            this.exportService = exportService;
        }

        private readonly ApplicationDbContext dbContext;
        private readonly RecordService recordService;
        private readonly ExportService exportService;

        /// <summary>
        /// 获取待审核的请求
        /// </summary>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public async Task<IActionResult> GetPendingRequests()
        {
            var teacher = this.GetIdentifier();
            return Ok(await recordService.GetPendingReviewRequestsAsync(teacher));
        }

        /// <summary>
        /// 获取操作记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public async Task<IActionResult> GetReviewHistory()
        {
            var teacher = this.GetIdentifier();
            return Ok(await recordService.GetReviewHistory(teacher));
        }

        /// <summary>
        /// 导出未核对学生列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public async Task<IActionResult> ExportUnfinishedStudents()
        {
            var teacher = this.GetIdentifier();
            return new XlsxFileResult(await exportService.ExportUnFinishedStudents(teacher));
        }

        /// <summary>
        /// 导出核对完成学生列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public async Task<IActionResult> ExportStudents()
        {
            var teacher = this.GetIdentifier();
            return new XlsxFileResult(await exportService.ExportStudents(teacher));
        }
        
        /// <summary>
        /// 审核请求
        /// </summary>
        /// <param name="requestId"></param>
        /// <param name="act"></param>
        /// <param name="reason"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        [HttpGet("[Action]/{act}")]
        public async Task<IActionResult> ReviewRequest(int requestId, string act, string reason)
        {
            var newStatus = act switch
            {
                "accept" => Status.Finished,
                "decline" => Status.Declined,
                _ => throw new InvalidOperationException()
            };

            var requestQuery = dbContext.Records.Where(x => x.Id == requestId);

            // 不存在的请求Id
            if (!requestQuery.Any()) return BadRequest();
            var request = requestQuery.Include(x => x.Student).ThenInclude(x => x.Counsellor).Single();

            // 不是这个老师的学生
            var teacher = this.GetIdentifier();
            if (request.Student.CounsellorId != teacher) return BadRequest();

            request.Status = newStatus;
            request.Comment = reason;
            await dbContext.SaveChangesAsync();

            return Ok();
        }
    }
}
